# PBAR_Zspec_InterestingPlots.py
#
#  Interesting plots to show group.
#
#  5/2/2013, John Kwong

#####################
##  Spectra plots  ##
#####################

# SPECTRA for multiple datasets, single detector
detector = 88
detector = 59

# plotList = plotList_CollimatorClosed
plotList = (datasetGroupsIndices['Pb'], datasetGroupsIndices['Fe'], datasetGroupsIndices['Al'])
#plotList = (datasetGroupsIndices['Pb'], datasetGroupsIndices['PbLS'])
#plotList = (datasetGroupsIndices['Fe'], datasetGroupsIndices['FeLS'])
#plotList = (datasetGroupsIndices['Al'], datasetGroupsIndices['AlLS'])
#plotList = (datasetGroupsIndices['Pb5_8'], datasetGroupsIndices['PbLS'])
##plotList = (datasetGroupsIndices['Fe12'], datasetGroupsIndices['FeLS'])
##plotList = (datasetGroupsIndices['Al30'], datasetGroupsIndices['AlLS'])

correctGain = 0
plotRate = 1;
fig = plt.figure()
kk = 0
for jj in np.arange(len(plotList)):
    subPlotList = plotList[jj]
    for ii in np.arange(len(subPlotList)):
        
        pp = subPlotList[ii]
        bins = np.arange(0,256)
        if correctGain:
            correction1 = gainExtrapolated[0,detector] / gainExtrapolated[pp,detector]    
        else:
            correction1 = 1.0
        correctionMat = np.matlib.repmat(1, 1, 256)[0]
        correctionMat[0:8] = 0
        if plotRate:
            plt.plot(bins * correction1, dat[pp][:,detector]/datasetAcquisitionTime[pp], \
                     ls = lineStyles[jj%5], color = plotColors[ii%7], \
                     label = (filenameList[pp]+ ', ' + datasetDescription[pp] + ', ' + datasetTimeStr[pp]))
        else:
            plt.plot(bins * correction1, dat[pp][:,detector], \
                     ls = lineStyles[jj%5], color = plotColors[ii%7], \
                     label = (filenameList[pp]+ ', ' + datasetDescription[pp] + ', ' + datasetTimeStr[pp]))
        kk = kk + 1
            
##plt.plot(np.array([0, 255, 255, 0, 0]), np.array([countRange[0], countRange[0], countRange[1], countRange[1], countRange[0]]))

if correctGain:
    plt.title('Detector #' + str(detector+1) + ', Gain Corrected')
else:
    plt.title('Detector #' + str(detector+1))
plt.legend(prop={'size':10})
plt.yscale('log')
##plt.yscale('linear')
plt.xlabel('Bin', fontsize = 16)

if plotRate:
    plt.ylabel('Rate', fontsize = 16)
else:
    plt.ylabel('Count', fontsize = 16)
plt.grid()
plt.xlim((0,250))
plt.show()


# GAIN SHIFT AS A FUNCTION OF ZSPEC DETECTOR NUMBER
plotList = datasetGroupsIndices['Pb']
plotList = datasetGroupsIndices['CC']

fig = plt.figure()
for ii in range(0,len(plotList)):
    pp = plotList[ii]
##    plt.plot(np.arange(1,138), gainExtrapolated[pp,:]/gainExtrapolated[plotList[0],:], \
##             marker = markerTypes[ii], label = (filenameList[pp]+ ', ' + datasetDescription[pp] + ', ' + datasetTimeStr[pp]))
    plt.plot(np.arange(1,137), gainExtrapolated[pp,:]/gainExtrapolated[plotList[0],:], \
             marker = markerTypes[ii], label = (datasetTimeStr[pp]))

plt.title('Gain Shift')
plt.legend(loc = 4, prop={'size':10})
plt.xlabel('Detector No.', fontsize = 12)
plt.ylabel('Gain Shift', fontsize = 12)
grid()
plt.show()

#  3D SCATTER PLOT OF DISCRIMINANTS Using collapsed array
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
correctx = 0
correctGain = 0
detectorList = goodDetectorsList[(goodDetectorsList>50) & (goodDetectorsList < 100)]
statsList = stats.keys()
# multibins
statName1 = 'binMean_g'
##statName1 = 'binSTD_g'
##statName1 = 'multibin_0_10_g'
##statName1 = 'multibin_0_20_g'
##statName1 = 'binMean_q50_g'

##statName2 = 'binSTD_binMean'
##statName2 = 'binSTD_g'
##statName2 = 'q_range_g'
##statName2 = 'multibin_10_ratio_g'
#statName2 = 'multibin_20_ratio_g'
##statName2 = 'multibin_0_20_g'
statName2 = 'binMean_q50_g'

##statName3 = 'binSTD_g'
##statName3 = 'multibin_20_256_g'
#statName3 = 'multibin_0_20_g'
statName3 = 'multibin_20_ratio_g'

transmissionRange = np.array((10000, 15000))
transmissionRange = np.array((7500, 12500))
transmissionRange = np.array((8500, 13000))
##transmissionRange = np.array((2200, 5200))

datasetGroupList = np.array(('PbALL', 'Pb', 'Fe', 'Al'))
datasetGroupList = np.array(('PbALL', 'PbNOT'))

kk = 0
for ii in range(len(datasetGroupList)):  # cycle through list of materials
    group = datasetGroupList[ii] # material cut
    # plt.plot(temp1[cutt[kk],:], temp2[cutt[kk],:], marker = markerTypes[kk], markersize=12, label = datasetDescription[cutt[kk]], color = plotColors[ii])
    transCutt = (statsCollapsed[group]['transmission'] > transmissionRange[0]) & (statsCollapsed[group]['transmission'] < transmissionRange[1])
##    plt.scatter(statsCollapsed[group][statName1][transCutt], statsCollapsed[group][statName2][transCutt], \
##                marker = markerTypes[kk], color = plotColors[ii%7], s = (15 + 30.0*(ii/7)), label = group)
    ax.scatter(statsCollapsed[group][statName1][transCutt], statsCollapsed[group][statName2][transCutt], statsCollapsed[group][statName3][transCutt], \
                    marker = markerTypes[kk], color = plotColors[ii%7], s = (15 + 30.0*(ii/7)), label = group)
    kk= kk + 1

plt.title('Transmission range: (' + str(transmissionRange[0]) + ', ' + str(transmissionRange[1]) + ')')
plt.xlabel(statName1)
plt.ylabel(statName2)
ax.set_zlabel(statName3) 
# plt.yscale('log')
plt.legend(loc = 1, prop={'size':10})
plt.show()


# MATRIX SCATTER PLOT OF DISCRIMINANTS
statsCollapseList = np.array((
            'binMean_g1', 'binMean_q50_g1', \
            'multibin_0_20_g1', 'multibin_20_256_g1', \
            'multibin_20_ratio_g1', 'transmission'))
numberStats = len(statsCollapseList) - 1

cutt = statsMatrix[:,-1] == 0
statsDataFrame = DataFrame(statsMatrix[:, 0:5], columns = statsCollapseList[0:-1])
#ax = pd.tools.plotting.scatter_matrix(statsDataFrame.ix[cutt], alpha=0.2, figsize=(5, 5), diagonal='kde')
ax = pd.tools.plotting.scatter_matrix(statsDataFrame.ix[cutt], alpha=0.2, figsize=(numberStats, numberStats), diagonal = 'hist')
subplotx = numberStats
subploty = numberStats
#f, ax = plt.subplots(subploty, subplotx, sharex='col', sharey='row')
cutt = statsMatrix[:,-1] == 1
for ii in np.arange(numberStats):
    for jj in np.arange(numberStats):
        if ii == jj:
            ax[ii][jj].hist(statsMatrix[cutt,ii], bins = 20)
        else:
            ax[ii][jj].plot(statsMatrix[cutt,jj], statsMatrix[cutt,ii], '.r', alpha = 0.2)
show()


# DISTANCE VERSUS TRANSMISSION
transmission = statsMatrix[:,-2]
dist0 = np.sum(np.matlib.repmat(wMean, featuresAllTransmission.shape[0], 1) * featuresAllTransmission, axis = 1)
plt.figure()
plt.scatter(transmission, dist0, c = targetsAllTransmission, s = 25, edgecolor=None, alpha = 0.2)
plt.xlabel('Transmission')
plt.ylabel('Distance')
plt.grid()
show()

# HISTOGRAM OF DISTANCE IN TRANSMISSION CUT

binEdges = np.linspace(0, 400, 200)
binCenters = (binEdges[1:] + binEdges[:-1])/2
counts = np.zeros((2, len(binCenters)))

for ii in np.arange(2):
    cut = targets == ii
    dist1 = np.sum(np.matlib.repmat(wMean, features.shape[0], 1) * features, axis = 1)
    counts[ii,:], bin = np.histogram(dist1[cut], bins = binEdges)

figure()
for ii in np.arange(2):
    plot(binCenters, counts[ii,:], label = groupNamesExportList[ii])
plt.grid()
plt.xlabel('Distance')
plt.ylabel('Counts')
show()


# HISTOGRAMS WITH INCREMENTS OF VARIABLES
f, axAll = plt.subplots(1, featuresAllTransmission.shape[1])
for jj in range(featuresAllTransmission.shape[1]):
    ii = jj + 1

    disSubset = sum(np.matlib.repmat(wMean[topStatsIndices[0:ii]], features.shape[0], 1) * features[:,topStatsIndices[0:ii]], axis = 1)

    axAll[jj].hist(disSubset, bins = 30, label = 'distance subset')
    axAll[jj].set_title(str(jj))
    axAll[jj].set_title('Number of stats: ' + str(ii))
plt.legend()

show()

